package com.luqili.utils.pub.consver;

import java.nio.ByteBuffer;

/**
 * 转换工具
 *
 * @author
 */
public class ByteConverUtils {

    /**
     * Float[] 转 Byte[]
     *
     * @param src
     * @return
     */
    public static byte[] float2Byte(float[] src) {
        ByteBuffer bb = ByteBuffer.allocate(src.length * 4);
        for (float f : src) {
            bb.putFloat(f);
        }
        return bb.array();

    }

    /**
     * Byte[] 转 Float[]
     *
     * @param src
     * @return
     */
    public static float[] byte2float(byte[] src) {
        if (src.length % 4 > 0) {
            throw new RuntimeException("数组长度错误");
        }
        ByteBuffer bb = ByteBuffer.allocate(src.length);
        bb.put(src);
        bb.clear();
        float[] fs = new float[src.length / 4];
        for (int i = 0; i < fs.length; i++) {
            fs[i] = bb.getFloat();
        }
        return fs;
    }

    /**
     * 合并数组
     *
     * @param arrays
     * @return
     */
    public static byte[] concat(byte[]... arrays) {
        int length = 0;
        for (byte[] array : arrays) {
            length += array.length;
        }
        byte[] result = new byte[length];
        int pos = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, pos, array.length);
            pos += array.length;
        }
        return result;
    }
}
